package com.sf.wisdomkg.activity;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.common.api.GoogleApiClient;
import com.sf.wisdomkg.R;
import com.sf.wisdomkg.adapter.HomeListViewAdapter;
import com.sf.wisdomkg.adapter.PopupWindowListViewAdapter;
import com.sf.wisdomkg.adapter.home_viewPaper_Adapter;
import com.sf.wisdomkg.utils.CommonUtils;
import com.sf.wisdomkg.utils.GlideImageLoader;
import com.sf.wisdomkg.utils.OnButtonCallback;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * Created by Administrator on 2017/9/19.
 */
public class HomeActivity extends AppCompatActivity implements View.OnClickListener,RongIM.UserInfoProvider {
    private static final String SHARE_CONTENT = "app_";
    private SharedPreferences setting;

    private ArrayList<String> imageIds;
    // private ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService;
    private ArrayList<HashMap<String, String>> lv_list;

    private TextView class_type;

    //公告UI
    private TextView popup_title,popup_title1,popup_content,popup_bottom;
    private String  popup_title_desc,popup_title1_desc,popup_content_desc,popup_bottom_desc;
    /**
     * 显示小圆点的布局
     */
    private LinearLayout linearlayout_cateinfo_dot;

    private ArrayList<HashMap<String, String>> arrayList;


    private String baseUrl1 = null;
    private String parentName = null;
    private String headImgl;

    // 图片封装为一个数组
    private int[] icon = {R.mipmap.dyna_class_icon, R.mipmap.online_baby_icon,
            R.mipmap.attendance_icon, R.mipmap.courses_icon, R.mipmap.album_icon, R.mipmap.clock_icon, R.mipmap.bus_school_iocn, R.mipmap.more_icon};
    private String[] iconName = {"班级动态", "宝宝在线", "考勤", "班级课程", "班级相册", "打卡", "校车", "更多"};
    //中间GridView
    private GridView gview;
    private List<Map<String, Object>> data_list;
    private SimpleAdapter sim_adapter;

    //底部新闻
    private ListView bottom_list;
    private ArrayList<HashMap<String, String>> list_view;
    private HomeListViewAdapter homeListViewAdapter;

    //UI
    private ImageView share_img, dropdown_img;
    private LinearLayout dropdown_ll;

    //弹窗UI
    private PopupWindow popupWindow;
    private ListView lvDr;
    private String window_type = null;
    private PopupWindowListViewAdapter popupWindowListViewAdapter;
    private ArrayList<HashMap<String, String>> popupArray;

    //控制广告popupwindow
    private boolean isPopup = true;
    private PopupWindow popWindow;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    //班级部分变量
    private String ClassId ;
    private String ClassTeacher;
    private ArrayList<String> images;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        initview();

        getNewInfo();
        setGridView();
        ClassList();
        getTopBanner();
//        check_userInfo(setting.getString("userName",""));

        connect(setting.getString("token",""));
        RongIM.setUserInfoProvider(this,true);
//        popWindow();
        share_img.setOnClickListener(this);
        dropdown_img.setOnClickListener(this);
        dropdown_ll.setOnClickListener(this);

        gview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                switch (i) {
                    case 0:
//                        HashMap<String, Boolean> hashMap = new HashMap<>();
//                        //会话类型 以及是否聚合显示
//                        hashMap.put(Conversation.ConversationType.PRIVATE.getName(),false);
//                        hashMap.put(Conversation.ConversationType.PUSH_SERVICE.getName(),true);
//                        hashMap.put(Conversation.ConversationType.SYSTEM.getName(),true);
//
//                        RongIM.getInstance().startConversationList(HomeActivity.this,hashMap);
                        if (setting.getString("roleId","").equals("3")){
                            RongIM.getInstance().startConversation(HomeActivity.this,
                                    Conversation.ConversationType.PRIVATE, setting.getString("teacherPhone",""), setting.getString("teacherName",""));
                        }else {
                            Intent intent = new Intent(HomeActivity.this,TalkingParentListActivity.class);
                            startActivity(intent);
                        }
                        break;
                    case 1:
                        Intent intent = new Intent(HomeActivity.this, BabyOnlineActivity.class);
                        Bundle bundle = new Bundle();
                        if (setting.getString("roleId","").equals("3")){

                            bundle.putString("loginId",setting.getString("returnId",""));
                        }else {
//                            bundle.putString("loginId",setting.getString("sessionId",""));
                            CommonUtils.confirm_info(HomeActivity.this,"暂未开放");
                            return;
                        }

                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case 2:
                        Intent intent1 = new Intent(HomeActivity.this, KaoQinListActivity.class);
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("id",ClassId);
                        intent1.putExtras(bundle1);
                        startActivity(intent1);
                        break;

                }
            }
        });
        bottom_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(HomeActivity.this, HomeInfoActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {

        if (hasFocus && isPopup) {
            isPopup = false;
            GetGongGao();
        }
        super.onWindowFocusChanged(hasFocus);
    }

    /**
     * 初始化数据
     */
    private void initview() {


        data_list = new ArrayList<Map<String, Object>>();
        gview = (GridView) findViewById(R.id.gview);
        list_view = new ArrayList<>();
        bottom_list = (ListView) findViewById(R.id.new_list);
        share_img = (ImageView) findViewById(R.id.share_img);
        dropdown_img = (ImageView) findViewById(R.id.dropdown_img);
        dropdown_ll = (LinearLayout) findViewById(R.id.dropdown_ll);
        class_type = (TextView)findViewById(R.id.class_type);

        popupArray = new ArrayList<>();
        images = new ArrayList<>();
        arrayList = new ArrayList<>();

        setting = this.getSharedPreferences(SHARE_CONTENT,0);
        if (setting.getString("roleId","").equals("2")){
            baseUrl1 = CommonUtils.IP_S + CommonUtils.M_T;
        }else if (setting.getString("roleId","").equals("3")){
            baseUrl1 = CommonUtils.IP_S + CommonUtils.M_S;
        }else if (setting.getString("roleId","").equals("1")){
            baseUrl1 = CommonUtils.IP_S + CommonUtils.M_T;
        }
    }

    /**
     * 初始化gridView
     */
    private void setGridView() {
        getData();
        String[] from = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        sim_adapter = new SimpleAdapter(HomeActivity.this, data_list, R.layout.home_gridview_item, from, to);
        //配置适配器
        gview.setAdapter(sim_adapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share_img:
//                new ShareAction(HomeActivity.this)
//                        .withText("hello")
//                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA)
//                        .setCallback(umShareListener)
//                        .open();
                break;
            case R.id.dropdown_ll:
                String items_price[] = {"班级一", "班级二", "班级三", "班级四", "班级五", "班级六"};
                if (window_type == null) {
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                    initType(view, items_price);
                } else {
                    window_type = null;
                    popupWindow.dismiss();
                }
                break;
            case R.id.close:
                popWindow.dismiss();
                break;
        }
    }

    /**
     * 加载gridview数据
     *
     * @return
     */
    public List<Map<String, Object>> getData() {
        //cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            data_list.add(map);
        }

        return data_list;
    }



    /**
     * 组合弹窗类别筛选数组
     *
     * @param strings
     */
    private void initType(View view, String[] strings) {

        if (setting.getString("roleId","").equals("3")||setting.getString("roleId","").equals("2")){
           return;
        }else{
            showPopupWindow(view);
        }

    }

    /**
     * 班级筛选
     *
     * @param view
     * @param
     */
    @SuppressWarnings("deprecation")
    @SuppressLint({"InflateParams", "NewApi"})
    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(HomeActivity.this).inflate(
                R.layout.home_banji_popmenu, null);
        lvDr = (ListView) contentView.findViewById(R.id.listH);
        LinearLayout ly = (LinearLayout) contentView.findViewById(R.id.bbb);

        popupWindowListViewAdapter = new PopupWindowListViewAdapter(HomeActivity.this, popupArray);
        lvDr.setAdapter(popupWindowListViewAdapter);
        lvDr.setItemsCanFocus(true);
        lvDr.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        popupWindowListViewAdapter.notifyDataSetChanged();
        WindowManager wm = (WindowManager) this.getSystemService(
                Context.WINDOW_SERVICE);

        DisplayMetrics ds = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(ds);
        px2dip(this, ds.widthPixels);
        popupWindow = new PopupWindow(contentView, ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.FILL_PARENT);

        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);

        popupWindow.update();
        ly.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                window_type = null;
                popupWindow.dismiss();
            }
        });

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                window_type = null;
            }
        });
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : " + event);

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        lvDr.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                class_type.setText(popupArray.get(arg2).get("name"));
                ClassId = popupArray.get(arg2).get("id");
                ClassTeacher = popupArray.get(arg2).get("teacher");
                popupWindow.dismiss();
                popupWindowListViewAdapter.selectIndex_FangXing = arg2;
                popupWindowListViewAdapter.notifyDataSetChanged();


            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        popupWindow.showAsDropDown(view, 25, 30);
        backgroundAlpha(0.4f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }


    private void popWindow() {
        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());//获取一个填充器
        View view = inflater.inflate(R.layout.popwindow, null);//填充我们自定义的布局
        Display display = getWindowManager().getDefaultDisplay();//得到当前屏幕的显示器对象

        //初始化UI

        Button button = (Button) view.findViewById(R.id.close);
        button.setOnClickListener(this);

        popup_title = (TextView)view.findViewById(R.id.popup_title);
        popup_title1 = (TextView)view.findViewById(R.id.popup_title1);
        popup_content = (TextView)view.findViewById(R.id.popup_content);
        popup_bottom = (TextView)view.findViewById(R.id.popup_bottom);

        popup_title.setText(popup_title_desc);
        popup_title1.setText(popup_title_desc);
        popup_content.setText("\t\t"+popup_content_desc);
        popup_bottom.setText(popup_bottom_desc);

        Point size = new Point();//创建一个Point点对象用来接收屏幕尺寸信息
        display.getSize(size);//Point点对象接收当前设备屏幕尺寸信息
        int width = size.x;//从Point点对象中获取屏幕的宽度(单位像素)
        int height = size.y;//从Point点对象中获取屏幕的高度(单位像素)
        Log.v("zxy", "width=" + width + ",height=" + height);//width=480,height=854可知手机的像素是480x854的
        //创建一个PopupWindow对象，第二个参数是设置宽度的，用刚刚获取到的屏幕宽度乘以2/3，取该屏幕的2/3宽度，从而在任何设备中都可以适配，高度则包裹内容即可，最后一个参数是设置得到焦点
        popWindow = new PopupWindow(view, 3 * width / 4, (int) ((3*width/4)*1.5), true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());//设置PopupWindow的背景为一个空的Drawable对象，如果不设置这个，那么PopupWindow弹出后就无法退出了
        popWindow.setOutsideTouchable(true);//设置是否点击PopupWindow外退出PopupWindow
        WindowManager.LayoutParams params = getWindow().getAttributes();//创建当前界面的一个参数对象
        params.alpha = 0.8f;//设置参数的透明度为0.8，透明度取值为0~1，1为完全不透明，0为完全透明，因为android中默认的屏幕颜色都是纯黑色的，所以如果设置为1，那么背景将都是黑色，设置为0，背景显示我们的当前界面
        getWindow().setAttributes(params);//把该参数对象设置进当前界面中
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {//设置PopupWindow退出监听器
            @Override
            public void onDismiss() {//如果PopupWindow消失了，即退出了，那么触发该事件，然后把当前界面的透明度设置为不透明
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                getWindow().setAttributes(params);
            }
        });
        //第一个参数为父View对象，即PopupWindow所在的父控件对象，第二个参数为它的重心，后面两个分别为x轴和y轴的偏移量
        popWindow.showAtLocation(findViewById(R.id.layout), Gravity.CENTER, 0, 0);


    }

    /**
     * 分享回调
     */
    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(HomeActivity.this, "成功了", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(HomeActivity.this, "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(HomeActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token) {

        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            /**
             * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
             *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
             */
            @Override
            public void onTokenIncorrect() {
            }

            /**
             * 连接融云成功
             * @param userid 当前 token 对应的用户 id
             */
            @Override
            public void onSuccess(String userid) {
                Log.d("LoginActivity", "--onSuccess" + userid);
                System.out.println("连接融云成功" + userid);
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                System.out.println("连接融云失败" + errorCode);
            }
        });

    }

    @Override
    public UserInfo getUserInfo(String s) {
        System.out.println("获取到用户的id"+s);
        check_userInfo(s);
        if (parentName!= null){
            if (!parentName.equals("")){
                return new UserInfo(s,parentName,Uri.parse(headImgl));
            }

        }
        return null;
    }


    /**
     * 获取首页班级列表
     */
    private void ClassList() {
        RequestParams params = new RequestParams(baseUrl1 + "class/getClassesList");

      if (setting.getString("roleId","").equals("3")){
            params.addParameter("returnId",setting.getString("returnId",""));
      }else{
            params.addParameter("userName",setting.getString("userName",""));
      }
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("班级"+result);
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                if (setting.getString("roleId","").equals("3")){
                                    JSONObject jsonObj = new JSONObject(jsonObject.optString("data"));
                                    class_type.setText(jsonObj.optString("name"));
                                    ClassId = jsonObj.optString("id");
                                    ClassTeacher = jsonObj.optString("teacher");
                                }else {
                                    JSONArray jsonArr = new JSONArray(jsonObject.optString("data"));
                                    JSONObject object = jsonArr.getJSONObject(0);
                                    class_type.setText(object.optString("name"));
                                    ClassId = object.optString("id");
                                    ClassTeacher = object.optString("teacher");
                                    for (int i = 0; i < jsonArr.length(); i++) {
                                        HashMap<String, String> hashMap = new HashMap<>();
                                        JSONObject jsObj = new JSONObject();
                                        jsObj = jsonArr.getJSONObject(i);
                                        hashMap.put("id", jsObj.optString("id"));
                                        hashMap.put("name", jsObj.optString("name"));
                                        hashMap.put("teacher", jsObj.optString("teacher"));
                                        popupArray.add(hashMap);
                                    }

                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("返回的错误"+ex);
                Toast.makeText(HomeActivity.this, "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(HomeActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取首页banner
     */
    private void getTopBanner() {

        RequestParams params = new RequestParams(baseUrl1 + "banner/bannerList");
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);
        System.out.println("得到轮播图"+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("得到轮播图"+result);
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                JSONArray jsonArr = new JSONArray(jsonObject.optString("data"));

                                for (int i = 0; i < jsonArr.length(); i++) {
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    JSONObject jsObj = new JSONObject();
                                    jsObj = jsonArr.getJSONObject(i);
                                    hashMap.put("img", jsObj.optString("img"));
                                    hashMap.put("id", jsObj.optString("id"));
                                    hashMap.put("content", jsObj.optString("content"));
                                    arrayList.add(hashMap);
                                    System.out.println("链接地址"+CommonUtils.IP_S+jsObj.optString("img"));
                                    images.add(CommonUtils.IP_S+jsObj.optString("img"));
                                    Banner banner = (Banner) findViewById(R.id.banner);
                                    banner.setImages(images).setImageLoader(new GlideImageLoader()).start();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("报错"+ex);
                Toast.makeText(HomeActivity.this, "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(HomeActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取信息公告
     */
    private void getNewInfo() {

        RequestParams params = new RequestParams(baseUrl1 + "notice/noticeList");
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                JSONArray jsonArr = new JSONArray(jsonObject.optString("data"));

                                for (int i = 0; i < jsonArr.length(); i++) {
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    JSONObject jsObj = new JSONObject();
                                    jsObj = jsonArr.getJSONObject(i);
                                    hashMap.put("id", jsObj.optString("id"));
                                    hashMap.put("name", jsObj.optString("name"));
                                    hashMap.put("content", jsObj.optString("content"));
                                    hashMap.put("user",jsObj.optString("user"));
                                    hashMap.put("createTime",jsObj.optString("createTime"));
                                    list_view.add(hashMap);
                                }
                                homeListViewAdapter = new HomeListViewAdapter(HomeActivity.this, list_view);
                                bottom_list.setAdapter(homeListViewAdapter);
                                homeListViewAdapter.notifyDataSetChanged();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                Toast.makeText(HomeActivity.this, "连接服务器失败,请检查网络！" + ex, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(HomeActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取信息公告
     */
    private void GetGongGao() {

        RequestParams params = new RequestParams(baseUrl1 + "affiche/afficheList");
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);
        System.out.println("获取的公告信息"+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("获取的公告信息"+ result);
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                JSONArray jsonArr = new JSONArray(jsonObject.optString("data"));
                                JSONObject jsObj = new JSONObject();
                                jsObj = jsonArr.getJSONObject(0);
                                popup_title_desc = jsObj.optString("title");
                                popup_title1_desc = jsObj.optString("title");
                                popup_content_desc = jsObj.optString("content");
                                popup_bottom_desc = jsObj.optString("createTime");

                                popWindow();
//                                popup_title.setText(jsObj.optString("title"));
//                                private TextView popup_title,popup_title1,popup_content,popup_bottom;
//                                for (int i = 0; i < jsonArr.length(); i++) {
//                                    HashMap<String, String> hashMap = new HashMap<>();
//                                    JSONObject jsObj = new JSONObject();
//                                    jsObj = jsonArr.getJSONObject(i);
//                                    hashMap.put("id", jsObj.optString("id"));
//                                    hashMap.put("name", jsObj.optString("name"));
//                                    hashMap.put("content", jsObj.optString("content"));
//                                    hashMap.put("user",jsObj.optString("user"));
//                                    hashMap.put("createTime",jsObj.optString("createTime"));
//                                    list_view.add(hashMap);
//                                }
//                                homeListViewAdapter = new HomeListViewAdapter(HomeActivity.this, list_view);
//                                bottom_list.setAdapter(homeListViewAdapter);
//                                homeListViewAdapter.notifyDataSetChanged();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                Toast.makeText(HomeActivity.this, "连接服务器失败,请检查网络！" + ex, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(HomeActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }
    public void check_userInfo(final String userId) {
        RequestParams params;
        if (setting.getString("roleId","").equals("3")){
             params = new RequestParams(baseUrl1+"parent/getOneByPhone");

        }else {
            params = new RequestParams(baseUrl1+"teacher/getOneByPhone");
        }


        //参数设置
        params.addParameter("phone", userId);

        //联网设置
        params.setCacheMaxAge(1000*60);
        params.setConnectTimeout(9000);
        System.out.println("用户信息"+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("用户信息"+result);
                //解析result
                if (result != null){
                    try {
                        JSONObject jsonObject  = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            JSONObject strArray;
                            try {
                                strArray = new JSONObject(jsonObject
                                        .optString("data"));

                                if (strArray.optString("name").equals("")){
                                    parentName = "万博会员";
                                }else {
                                    parentName = strArray
                                            .optString("name");
                                }
                                if (setting.getString("roleId","").equals("3")){
                                    if (strArray.optString("sex").equals("0")){
                                        headImgl = "http://60.205.214.21:8080/app/boy_head_icon.png";
                                    }else {
                                        headImgl = "http://60.205.214.21:8080/app/girl_head_icon.png";
                                    }
                                }else {
                                    headImgl = "http://60.205.214.21:8080/app/teacher_woman.png";
                                }

//                                /**
//                                 * 刷新用户缓存数据。
//                                 *
//                                 * @param userInfo 需要更新的用户缓存数据。
//                                 */
                             RongIM.getInstance().refreshUserInfoCache(new UserInfo(userId, parentName, Uri.parse(headImgl)));
//
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

//				Toast.makeText(getActivity(), "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
//				Toast.makeText(getActivity(), "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

}
